import { execSync } from "child_process"

export function analyzeModifiedLines() {
  // 获取最后一次提交的作者信息
  // 获取Git基础信息
  const commitHash = execSync('git rev-parse HEAD').toString().trim();
  const commitTime = execSync('git log -1 --format="%aI"').toString().trim();
  const email = execSync('git log -1 --format="%ae"').toString().trim();
  const committerEmail = execSync('git log -1 --format="%ce"').toString().trim();
  const branch = execSync('git branch --show-current').toString().trim();
  const author = execSync('git log -1 --pretty=format:"%an <%ae>"').toString().trim();
  const projectName = execSync('basename $(git rev-parse --show-toplevel)').toString().trim();

  // 获取所有修改文件的精确行差异（统一格式处理）
  const rawDiff = execSync('git diff -U0 HEAD~1 HEAD').toString();
  const files = {};

  // 解析差异输出
  let currentFile = null;
  rawDiff.split('\n').forEach(line => {
    // 检测文件变更区块
    if (line.startsWith('diff --git')) {
      const match = /b\/(.+)$/.exec(line);
      currentFile = match ? match[1] : null;
      if (currentFile) files[currentFile] = { chunks: [] };
      return;
    }

    // 解析差异块行号（格式示例：@@ -10,5 +12,7 @@）
    if (currentFile && line.startsWith('@@')) {
      const newLineMatch = /\+(\d+),?(\d*)/.exec(line);
      if (newLineMatch) {
        files[currentFile].chunks.push({
          start: parseInt(newLineMatch[1]),
          lineCount: newLineMatch[2] ? parseInt(newLineMatch[2]) : 1
        });
      }
      return;
    }
  });

  // 二次扫描获取AI标记范围
  Object.keys(files).forEach(file => {
    const content = execSync(`git show HEAD:${file} 2>/dev/null || echo ""`).toString();
    let aiRanges = [];
    let inBlock = false;
    let blockStart = 0;

    content.split('\n').forEach((line, i) => {
      if (line.includes('@ai-start')) {
        inBlock = true;
        blockStart = i + 1; // 转为1-based行号
      } else if (line.includes('@ai-end')) {
        if (inBlock) aiRanges.push({ start: blockStart, end: i });
        inBlock = false;
      }
    });

    files[file].aiRanges = aiRanges;
  });

  return {
    meta: {
      commit_hash: commitHash,
      commit_time: commitTime,
      email: email,
      committer_email: committerEmail,
      branch: branch,
      author: author,
      recorded_at: new Date().toISOString(),
      project_name: projectName
    },
    files: files
  };
}

export function isLineInAIRanges(lineNum, aiRanges) {
  return aiRanges.some(range => lineNum >= range.start && lineNum <= range.end);
}